package models

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"time"
)

type Notification struct {
	Id         int
	CategoryId int    `valid:"Required"`
	Title      string `valid:"Required"`
	Summary    string
	Content    string
	CreateAt   int64
	IfSchedule int
	SendTime   int64
	CancelTime int64
	DeleteTime int64
}

type NotificationQueryParam struct {
	BaseQueryParam
	Title string
}

func init() {
	orm.RegisterModel(new(Notification))
}

func (this *Notification) TableName() string {
	return NotificationTBName()
}

func NotificationTBName() string {
	return TableName("notification")
}

// 如果你的 struct 实现了接口 validation.ValidFormer
// 当 StructTag 中的测试都成功时，将会执行 Valid 函数进行自定义验证
func (u *Notification) Valid(v *validation.Validation) {
	//if strings.Index(u.Name, "admin") != -1 {
	//	// 通过 SetError 设置 Name 的错误信息，HasErrors 将会返回 true
	//	v.SetError("Name", "名称里不能含有 admin")
	//}
}

func NotificationOne(id int) (*Notification, error) {
	o := orm.NewOrm()
	m := Notification{Id: id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

func NotificationPageList(params *NotificationQueryParam) ([]*Notification, int64) {
	query := orm.NewOrm().QueryTable(NotificationTBName())
	data := make([]*Notification, 0)

	sort := "Id"
	switch params.Sort {
	case "Id":
		sort = "Id"
	}

	if params.Order == "desc" {
		sort = "-" + sort
	}

	if len(params.Title) > 0 {
		query = query.Filter("title__istartswith", params.Title)
	}

	total, _ := query.Count()
	query.OrderBy(sort).Limit(params.Limit, params.Offset).All(&data)
	return data, total
}

func NotificationDelete(id int) bool {
	o := orm.NewOrm()
	query := o.QueryTable(NotificationRecipientTBName())
	m, err := NotificationOne(id)
	m.DeleteTime = time.Now().Unix()
	if err != nil {
		return false
	}

	if _, err := o.Update(&m); err == nil {
		query.Filter("notification_id", id).Delete()
		return true
	}
	return false
}
